/*
 @description: 网站设置（头尾）

 @author: 李建翰

 @update: 2021年9月7日14:44:27
*/
'use strict';
const Controller = require('egg').Controller;
//const fs = require('fs');
//const moment = require('moment');
class SetUpCpntroller extends Controller{
    
    async index() { //搜索
        const {ctx,app} = this;
        const {keyname} = ctx.request.query
        let where=''
        if(keyname){
            where=`where fuxiao_title like "%${keyname}%"`
        }
        const result =await app.mysql.query(`select * from fuxiao_setup ${where}`)
        ctx.body = {
            code:0,
            msg:"查找成功",
            data:result
        }
    }

            
            //改
            async update() {//put
                const {ctx,app} =this;
                const {logo,about,privacy,copyright,hotline} = ctx.request.body
                const {id} = ctx.params;
                const row={
                    logo,
                    about,
                    privacy,
                    copyright,
                    hotline
                };
                const options={
                    where:{
                        id:+id
                    }
                };
                const result = await app.mysql.update('fuxiao_setup',row,options);
                console.log(id,logo,
                    about,
                    privacy,
                    copyright,
                    hotline);

            const path = await app.mysql.query(`select 	logo from fuxiao_setup where id=${+id}`);
            
            if (path[0].logo!==logo) {
                fs.unlink(`app/${path[0].logo}`, (err) => {
                    if (err) throw err;
                });
            }

            const path1 = await app.mysql.query(`select 	hotline from fuxiao_setup where id=${+id}`);
            
            if (path1[0].hotline!==hotline) {
                fs.unlink(`app/${path[0].hotline}`, (err) => {
                    if (err) throw err;
                });
            }
                    if(result){
                        ctx.body={
                            code:0,
                            msg:"编辑成功",
                        };
                    }else{
                        ctx.body={
                            code:4008,
                            msg:"编辑失败",
                        };
                    } 
            }

            //删除
            async destroy() { //DELETE
                const {ctx,app} = this;
                const {id} = ctx.params;
                const result =await app.mysql.delete(`fuxiao_setup`,{id:+id})
                if(result){
                    ctx.body = {
                        code: 0,
                        msg: "删除成功",
                    };
                }else{
                    ctx.body = {
                        code: 4007,
                        msg: "删除失败",
                    }; 
                }
                }
}
module.exports = SetUpCpntroller